package ca.abubakrsagar.breadboardsim;

import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class WireController implements MouseListener {
	private BreadboardPanel brPanel; // The breadboard panel associated with the mouse
								// listener.
	private Point parentPos; // The location of the parent component.
	private Point mouseOnScreen; // The point of the mouse on the screen.
	private Point point1, point2; // Two points used to keep track of where the wire
							// must go.

	/**
	 * Creates a new wire controller while associating the given breadboard
	 * panel with the local breadboard panel. Additionally initilizes two points
	 * that will be used for the two points of the line.
	 * 
	 * @param brPanel
	 *            The breadboard panel to be drawn upon.
	 */
	public WireController(BreadboardPanel brPanel) {
		this.brPanel = brPanel;
		point1 = new Point();
		point2 = new Point();
		//Set point 1 to -1, used to keep track of if it is the first click.
		point1.x = -1;
	}

	/**
	 * Handle the clicks by the user. When the user right clicks two grids
	 * either vertically or horizontally across, a new wire is created between
	 * those points.
	 */
	public void mouseClicked(MouseEvent e) {
		parentPos = brPanel.getLocationOnScreen();
		mouseOnScreen = e.getLocationOnScreen();
		// If the mouse is right clicked.
		if (e.getButton() == 3) {
			if (point1.x == -1) { // If it's the first right click.
				point1.x = mouseOnScreen.x - parentPos.x;
				point1.y = mouseOnScreen.y - parentPos.y;
				System.out.println(point1.x + " " + point1.y);
			} else {
				point2.x = mouseOnScreen.x - parentPos.x;
				point2.y = mouseOnScreen.y - parentPos.y;
				System.out.println(point2.x + " " + point2.y);
				// If the two clicks are horizontal or vertical, create a new
				// wire.
				if ((point2.x - point1.x <= 6) || (point2.y - point1.y <= 6)) {
					brPanel.addWire(point1.x, point1.y, point2.x, point2.y);
				}
				point1.x = -1; // Reset to be first right click.

			}
		}
	}

	public void mouseEntered(MouseEvent e) {

	}

	public void mouseExited(MouseEvent e) {

	}

	public void mousePressed(MouseEvent e) {

	}

	public void mouseReleased(MouseEvent e) {

	}
}
